package dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.*;
import android.util.Log;
import dao.DatabaseHelper;

import beans.Product;

public class ProductDAO {
	
	private DatabaseHelper dbHelper;
	private SQLiteDatabase dbWrite;
	private SQLiteDatabase dbRead;
	
	public ProductDAO(Context context){
		this.dbHelper = new DatabaseHelper(context);
		this.dbWrite = this.dbHelper.getWritableDatabase();
		this.dbRead = this.dbHelper.getReadableDatabase();
	}

	public Product returnProduct(String productEAN){

		
	    String selectQuery = "SELECT  * FROM " + this.dbHelper.getTable_product() + " WHERE "
	            + this.dbHelper.getKey_id() + " = " + productEAN;
	 
	    Cursor c = dbRead.rawQuery(selectQuery, null);
	 
	    if (c != null){
	        c.moveToFirst();
	    }
		Product product = new Product();
		product.setEANProduct(c.getString(c.getColumnIndex(this.dbHelper.getKey_id())));
		product.setName((c.getString(c.getColumnIndex(this.dbHelper.getKey_product_name()))));
		
		return product;
	}
	
	public List<Product> returnListProducts(){

		
	    String selectQuery = "SELECT  * FROM " + this.dbHelper.getTable_product();
	    List<Product> productList = new ArrayList<Product>();
	    Cursor c = dbRead.rawQuery(selectQuery, null);
	 
	    // looping through all rows and adding to list
	    if (c.moveToFirst()) {
	        do {

	    		Product product = new Product();
	    		product.setEANProduct(c.getString(c.getColumnIndex(this.dbHelper.getKey_id())));
	    		product.setName((c.getString(c.getColumnIndex(this.dbHelper.getKey_product_name()))));
	 

	            // adding to servicos list
	    	    productList.add(product);

			} while (c.moveToNext());
		}

		
		return productList;
	}
	
	public void insertProduct(Product product){

		
		ContentValues values = new ContentValues();
		values.put(this.dbHelper.getKey_EAN(), product.getEANProduct());
	    values.put(this.dbHelper.getKey_product_name(), product.getName());
	    
	    Log.d("DAO", product.getEANProduct());
	    Log.d("DAO", product.getName());

		

	}
	
	
	
}
